﻿namespace LMT.Db.Collections
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Reflection;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Text;

    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    [Serializable()]
    public class SerializeList<T> : List<T> where T : IDbEntity, new()
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="SerializeList"/> class.
        /// </summary>
        /// <param name="collection">The collection.</param>
        public SerializeList(IList<T> collection)
        {
            this.AddRange(collection);
        }

        /// <summary>
        /// Opens the specified file.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        /// <returns></returns>
        public static SerializeList<T> Open(string filePath)
        {
            byte[] content = File.ReadAllBytes(filePath);
            return SerializeList<T>.Open(content);
        }

        /// <summary>
        /// Opens the specified content.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <returns></returns>
        public static SerializeList<T> Open(byte[] content)
        {
            MemoryStream memStream = new MemoryStream(content);

            BinaryFormatter bformatter = new BinaryFormatter();
            SerializeList<T> instance = (SerializeList<T>)bformatter.Deserialize(memStream);
            memStream.Dispose();

            return instance;
        }

        /// <summary>
        /// Gets the serialize byte.
        /// </summary>
        /// <returns></returns>
        public byte[] GetSerializeByte()
        {
            MemoryStream memStream = new MemoryStream();
            BinaryFormatter bformatter = new BinaryFormatter();
            bformatter.Serialize(memStream, this);

            byte[] content = memStream.ToArray();

            memStream.Dispose();

            return content;
        }

        /// <summary>
        /// Saves the specified file path.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        public void Save(string filePath)
        {
            File.WriteAllBytes(filePath, this.GetSerializeByte());
        }
    }
}